import { Body, Controller, Get, Post, HttpException, UseGuards, Query } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthorBaseControll } from './authorBase.controller'
import { UserService } from '../services/user.service';
import { UserAccountDto } from '../dtos/user.dto'
import { AuthGuard } from '../guards/authority.guard'
import { CreateUserDto, UserIdDto, UserListDto } from '../dtos/user.dto';
import uuidCreate from '../utils/uuidCreate'
import { md5Create } from '../utils/md5Create'



@ApiTags("用户中心")
@Controller('/user')
@UseGuards(AuthGuard)
export class UserController extends AuthorBaseControll {
  constructor (private readonly userService: UserService) {
    super()
  }

  @Post('/checkUser')
  @ApiOperation({ summary: '判断用户是否存在' })
  async checkUserExistController(@Body() userAccountDto: UserAccountDto) {
    const result = await this.userService.checkUserExistService(userAccountDto)
    if (result.length > 0) {
      throw new HttpException('该用户已存在', 400);
    } else {
      return '该用户名可用'
    }
  }

  @Get('/getUserList')
  @ApiOperation({ summary: '显示用户列表' })
  async getUserList(@Query() userQuery: UserListDto) {
    return await this.userService.userList(userQuery)
  }

  @Post('/createUser')
  @ApiOperation({ summary: '创建用户' })
  async createUser(@Body() CreateUserDto: CreateUserDto) {
    CreateUserDto.fId = uuidCreate()
    CreateUserDto.fUserPassword = md5Create(CreateUserDto.fUserPassword)
    const userInfo = await this.userService.checkUserExistService(CreateUserDto.fUserAccount)
    if (userInfo.length === 0) {
      return await this.userService.createUser(CreateUserDto)
    } else {
      throw new HttpException('用户已存在', 404)
    }
  }

  @Get('/getUserById')
  @ApiOperation({ summary: '获取用户详情' })
  getUserById(@Query('fId') userId: string) {
    return this.userService.getUserById(userId)
  }

  @Post('/upDateUserById')
  @ApiOperation({ summary: '根据id修改用户信息' })
  updateUserById(@Body() CreateUserDto: CreateUserDto) {
    return this.userService.updateUserById(CreateUserDto)
  }

  @Post('/deleteUerById')
  @ApiOperation({ summary: '删除用户信息' })
  async deleteUserById(@Body() UserIdDto: UserIdDto) {
    const result = await this.userService.deleteUserById(UserIdDto)
    if (result.affectedRows === 1) {
      return {
        message: '成功删除用户'
      }
    } else {
      throw new HttpException('出错了,请联系管理员', 404)
    }
  }
}